// pages/publish/detail/index.js
import common from "../../../common/compents.js";
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import * as echarts from '../../ec-canvas/echarts.js';
let App = getApp();
let oneComponent = null,
  myMap, myOptions;
let oneComponent1 = null,
  myMap1, myOptions1;
let oneComponent2 = null,
  myMap2, myOptions2;
let oneComponent3 = null,
  myMap3, myOptions3;
let oneComponent4 = null,
  myMap4, myOptions4;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    infoPower: true,
    chartPower: true,
    historyPower: true,
    historyChartPower: true,
    basePower: true,
    relationPower: true,
    animationData: {},
    goodsId: 2788584,
    baseInfo: {},
    choose: 1,
    active: 0,
    // 销售走势
    kernelData: {
      sale_total_info: {
        now: 0,
        pre_compare: 0,
        last_compare: 0
      },
      sale_rank_info: {
        now: 0,
        pre_compare: 0,
        last_compare: 0
      },
      sale_cate_rank_info: {
        now: 0,
        pre_compare: 0,
        last_compare: 0
      }
    },
    lifeInfo: {
      sale_total: 0,
      publish_duration: 0
    },
    readerNum: 0,
    readerAvgBuy: 0,
    period: common.weekDate().weekth,
    date_type: 2,
    start_date: common.weekDate().start.replace(/-/g, ''),
    kernelChartList: [],
    saleTotalList: [],
    saleRankList: [],
    saleCateList: [],
    leftChartList: [],
    sexList: [],
    ageList: [],
    consumeList: [],
    regionList1: [],
    regionList2: [],
    relationList: [],
    showKernel: false,
    onInitChart: null,
    showLife: false,
    onInitLifeChart: null,
    showSex: false,
    onInitSexChart: null,
    showAge: false,
    onInitAgeChart: null,
    showConsume: false,
    onInitConsumeChart: null,
    isHand: false,
    shareShow: false,
    visible: true,
    ecChart: {
      lazyLoad: true //设置图表懒加载
    },
    kernelEchartsData: {},
    kernelChartSrc: '',
    lifeChartSrc: '',
    sexChartSrc: '',
    ageChartSrc: '',
    consumeChartSrc: '',
    time: '第' + common.weekDate().weekth.slice(-2) + '周 ' + common.weekDate().start + '~' + common.weekDate().end,
    trendHeight:0,
    lifeHeight:0,
    readerHeight:0,
    topHeight:0
  },
  // 获取商品基础信息
  getBaseInfo() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/goods/info',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        goods_id: that.data.goodsId
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            infoPower: true,
            relationPower: true,
            baseInfo: resapi.data.data,
          })
          that.getRelationData();
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            infoPower: false,
            relationPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取销售走势
  getKernelData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/goods/kerneldata',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        goods_id: that.data.goodsId,
        period: that.data.period,
        date_type: that.data.date_type,
        start_date: that.data.start_date,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          let _arr1 = [],
            _arr2 = [],
            _arr3 = [],
            _arr = [];
          that.setData({
            showKernel: false,
          })
          for (let i = 0; i < resapi.data.data.chart_data.sale_total.current_data.length; i++) {
            let _obj1 = resapi.data.data.chart_data.sale_total.current_data[i],
              _obj2;
            _obj1.type = "当期";
            _obj1.date = _obj1.date.toString();
            if (resapi.data.data.chart_data.sale_total.last_data) {
              _obj2 = resapi.data.data.chart_data.sale_total.last_data[i];
              _obj2.type = "上年同期";
              _obj2.date = _obj2.date.toString();
            }
            if (resapi.data.data.chart_data.sale_total.last_data) {
              _arr1.unshift(_obj2);
            }
            _arr1.unshift(_obj1);
          }
          for (let j = 0; j < resapi.data.data.chart_data.sale_rank.current_data.length; j++) {
            let _obj1 = resapi.data.data.chart_data.sale_rank.current_data[j],
              _obj2;
            _obj1.type = "当期";
            _obj1.date = _obj1.date.toString();
            if (resapi.data.data.chart_data.sale_rank.last_data) {
              _obj2 = resapi.data.data.chart_data.sale_rank.last_data[j];
              _obj2.type = "上年同期";
              _obj2.date = _obj2.date.toString();
            }
            if (resapi.data.data.chart_data.sale_rank.last_data) {
              _arr2.unshift(_obj2);
            }
            _arr2.unshift(_obj1);
          }
          for (let k = 0; k < resapi.data.data.chart_data.cate_rank.current_data.length; k++) {
            let _obj1 = resapi.data.data.chart_data.cate_rank.current_data[k],
              _obj2;
            _obj1.type = "当期";
            _obj1.date = _obj1.date.toString();
            if (resapi.data.data.chart_data.cate_rank.last_data) {
              _obj2 = resapi.data.data.chart_data.cate_rank.last_data[k];
              _obj2.type = "上年同期";
              _obj2.date = _obj2.date.toString();
            }
            if (resapi.data.data.chart_data.cate_rank.last_data) {
              _arr3.unshift(_obj2);
            }
            _arr3.unshift(_obj1);
          }
          if (that.data.choose == 1) {
            _arr = _arr1;
          } else if (that.data.choose == 2) {
            _arr = _arr2;
          } else if (that.data.choose == 3) {
            _arr = _arr3;
          }
          // console.log(_arr)
          that.setData({
            chartPower: true,
            kernelData: resapi.data.data.kernel_data,
            saleTotalList: _arr1,
            saleRankList: _arr2,
            saleCateList: _arr3,
            kernelChartList: _arr,
            onInitChart: (F2, config) => that.initKernelChart(F2, config, _arr),
            kernelEchartsData: resapi.data.data.chart_data,
            showKernel: true,
          })
          that.kernelEcharts();
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            chartPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取生命周期数据
  getLifeInfo() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/goods/history',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        goods_id: that.data.goodsId
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            historyPower: true,
            lifeInfo: resapi.data.data,
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            historyPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  getLifeChartData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/goods/historychart',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        goods_id: that.data.goodsId,
        date_type: 3
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            historyChartPower: true,
            showLife: false,
          })
          let _arr = [];
          for (let i = 0; i < resapi.data.data.length; i++) {
            let _obj = resapi.data.data[i];
            _obj.type = "销售指数";
            _arr.push(_obj);
          }
          that.setData({
            leftChartList: _arr,
            onInitLifeChart: (F2, config) => that.initLifeChart(F2, config, _arr),
            showLife: true,
          })
          that.lifeEcharts();
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            historyChartPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取读者画像数据
  getReaderData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/goods/reader/base',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        goods_id: that.data.goodsId
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            basePower: true,
            showSex: false,
            showAge: false,
            showConsume: false,
          })
          let _arr1 = [],
            _arr2 = [],
            _arr3 = [],
            total1 = 0,
            total2 = 0,
            total3 = 0;
          resapi.data.data.persona_sex.map((value, key) => {
            total1 += value.value;
          })
          resapi.data.data.persona_age.map((value, key) => {
            total2 += value.value;
          })
          resapi.data.data.persona_money.map((value, key) => {
            total3 += value.value;
          })
          resapi.data.data.persona_sex.map((value, key) => {
            let _obj = {};
            _obj.name = value.name;
            _obj.value = Number(((value.value / total1) * 100).toFixed(1));
            _arr1.unshift(_obj);
          })
          resapi.data.data.persona_age.map((value, key) => {
            let _obj = {};
            _obj.name = value.name;
            _obj.value = Number(((value.value / total2) * 100).toFixed(1));
            _arr2.unshift(_obj);
          })
          resapi.data.data.persona_money.map((value, key) => {
            let _obj = {};
            _obj.name = value.name;
            _obj.value = Number(((value.value / total3) * 100).toFixed(1));
            _arr3.unshift(_obj);
          })
          // console.log(_arr1,_arr2,_arr3)
          that.setData({
            readerNum: resapi.data.data.reader_num,
            readerAvgBuy: resapi.data.data.reader_avg_buy,
            sexList: _arr1,
            ageList: _arr2,
            consumeList: _arr3,
            regionList1: resapi.data.data.persona_region.slice(0, 5),
            regionList2: resapi.data.data.persona_region.slice(5, 10),
            onInitSexChart: (F2, config) => that.initSexChart(F2, config, _arr1),
            showSex: true,
            onInitAgeChart: (F2, config) => that.initAgeChart(F2, config, _arr2),
            showAge: true,
            onInitConsumeChart: (F2, config) => that.initConsumeChart(F2, config, _arr3),
            showConsume: true,
          })
          that.sexEcharts();
          that.ageEcharts();
          that.consumeEcharts();
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            basePower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
        let query = wx.createSelectorQuery();
        wx.nextTick(() => {
          query.select('.goods-top').boundingClientRect(function (rect3) {
            that.setData({
              topHeight: rect3.height
            })
          }).exec();
          query.select('.sale-trend').boundingClientRect(function (rect) {
            that.setData({
              trendHeight: rect.height
            })
          }).exec();
          query.select('.life-cycle').boundingClientRect(function (rect1) {
            that.setData({
              lifeHeight: rect1.height
            })
          }).exec();
          query.select('.readers').boundingClientRect(function (rect2) {
            that.setData({
              readerHeight: rect2.height
            })
          }).exec();
        })
      }
    })
  },
  // 获取商品关联搭配
  getRelationData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/goods/relation',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        isbn: that.data.baseInfo.isbn
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            relationPower: true,
            relationList: resapi.data.data,
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            relationPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 销售走势图表
  initKernelChart(F2, config, data) {
    let _dom = config,
      that = this;
    _dom.padding = [0, 0];
    const chart = new F2.Chart(_dom);
    chart.source(data);
    chart.axis(false);
    chart.tooltip({
      showCrosshairs: true,
      showTitle: true,
      offsetY: 45,
      background: {
        radius: 4,
        padding: [5, 10],
      },
      onShow(obj) {
        // console.log(obj)
        const items = obj.items;
        if (that.data.date_type == 2) {
          items[0].title = items[0].origin.date + '（' + items[0].origin.week_range + '）';
        }
      },
    });
    chart.legend(false);
    chart.line().position('date*value').color('type', (type) => {
      if (type == "当期") {
        return "#5A8BEE";
      } else if (type == "上年同期") {
        return "#D1DDF6";
      }
    }).size(1);
    chart.render();
    // 注意：需要把chart return 出来
    return chart;
  },
  kernelEcharts() {
    oneComponent = this.selectComponent('#kernelCanvas');
    let that = this,
      _obj,
      _arr1 = [],
      _arr2 = [],
      _arr3 = [];
    if (this.data.choose == 1) {
      _obj = this.data.kernelEchartsData.sale_total;
    } else if (this.data.choose == 2) {
      _obj = this.data.kernelEchartsData.sale_rank;
    } else if (this.data.choose == 3) {
      _obj = this.data.kernelEchartsData.cate_rank;
    }
    _obj.current_data.map((value, key) => {
      if (value.week_range) {
        _arr1.push(value.date + '（' + value.week_range + '）')
      } else {
        _arr1.unshift(value.date)
      }
      _arr2.unshift(value.value)
    })
    _obj.last_data.map((value, key) => {
      _arr3.unshift(value.value)
    })
    oneComponent.init((canvas, width, height, dpr) => {
      myMap = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myMap);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              show: false
            }
          },
          position: function (pos, params, dom, rect, size) {
            // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
            var obj = {
              top: '10%'
            };
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 10;
            return obj;
          },
          formatter(params) {
            console.log(params);
            let str = params[0].name + "\n";
            params.forEach((item) => {
              if (item.seriesName == '昨日' && params.length > 1) {
                str += item.seriesName + '：' + item.value + '\n';
              } else {
                str += item.seriesName + '：' + item.value;
              }
            })
            return str;
          }
        },
        color: ['#5A8BEE', '#D1DDF6'],
        legend: {
          show: false,
          data: ['当期', '上年同期']
        },
        grid: {
          show: false,
          left: 5,
          right: 5,
          bottom: 5,
          top: 0,
          containLabel: false
        },
        xAxis: [{
          show: false,
          type: 'category',
          // boundaryGap: false,
          data: _arr1
        }],
        yAxis: [{
          show: false,
          type: 'value'
        }],
        series: [{
            name: '当期',
            type: 'line',
            lineStyle: {
              width: 1
            },
            symbol: 'none',
            data: _arr2
          },
          {
            name: '上年同期',
            type: 'line',
            lineStyle: {
              width: 1
            },
            symbol: 'none',
            data: _arr3
          },
        ]
      };
      myOptions = option;
      myMap.setOption(option);
      return myMap
    });
  },
  // 生命周期图表
  initLifeChart(F2, config, data) {
    let _dom = config;
    _dom.padding = [0, 0];
    const chart = new F2.Chart(_dom);
    chart.source(data);
    chart.axis(false);
    chart.tooltip({
      showCrosshairs: true,
      showTitle: true,
      offsetY: 45,
      background: {
        radius: 4,
        padding: [5, 10],
      },
    });
    chart.legend(false);
    chart.line().position('date*value').color('type', (type) => {
      return "#5A8BEE";
    }).size(1);
    chart.render();
    // 注意：需要把chart return 出来
    return chart;
  },
  lifeEcharts() {
    oneComponent1 = this.selectComponent('#lifeCanvas');
    let that = this,
      _arr = [],
      _arr1 = [];
    this.data.leftChartList.map((value, key) => {
      _arr.push(value.date);
      _arr1.push(value.value);
    })
    oneComponent1.init((canvas, width, height, dpr) => {
      myMap1 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myMap1);
      const option = {
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          show: false,
          left: 5,
          right: 5,
          bottom: 5,
          top: 0,
          containLabel: false
        },
        xAxis: {
          show: false,
          type: 'category',
          data: _arr
        },
        yAxis: {
          show: false,
          type: 'value'
        },
        color: ['#5A8BEE'],
        series: [{
          name: "销售指数",
          data: _arr1,
          type: 'line',
          lineStyle: {
            width: 1
          },
          symbol: 'none',
        }]
      };
      myOptions1 = option;
      myMap1.setOption(option);
      return myMap1
    });
  },
  // 读者画像 
  // 性别
  initSexChart(F2, config, data) {
    let _dom = config;
    _dom.padding = [0, 10, 0, 35];
    const chart = new F2.Chart(_dom);
    const _data = data;
    _data.forEach(function (obj) {
      let textAlign;
      let offsetX;
      textAlign = 'start';
      offsetX = 5;
      chart.guide().text({
        position: [obj.name, obj.value],
        content: obj.value + '%',
        style: {
          textAlign,
          fill: '#07193F',
          fontWeight: 'bold',
          fontSize: 12
        },
        offsetX
      });
    });
    chart.source(_data.reverse(), {
      value: {
        min: 0,
        max: 100
      }
    });
    chart.coord({
      transposed: true
    });
    chart.axis('value', false);
    chart.axis('name', {
      grid: null,
      label: {
        fill: "#7789AF",
        fontSize: 12
      }
    });
    chart.interval().position('name*value').size(12);
    chart.render();
    return chart;
  },
  sexEcharts() {
    oneComponent2 = this.selectComponent('#sexCanvas');
    let that = this,
      _arr = [],
      _arr1 = [];
    for (let i = 0; i < this.data.sexList.length; i++) {
      _arr.unshift(this.data.sexList[i].name);
      _arr1.unshift(this.data.sexList[i].value);
    }
    oneComponent2.init((canvas, width, height, dpr) => {
      myMap2 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myMap2);
      const option = {
        grid: {
          show: false,
          left: 35,
          right: 5,
          bottom: 5,
          top: 0,
          containLabel: false
        },
        color: ["#1890FF"],
        xAxis: {
          show: false,
          type: 'value',
          max: 100,
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#7789AF',
              fontSize: 12
            }
          },
          data: _arr
        },
        series: [{
          type: 'bar',
          barWidth: 12,
          label: {
            show: true,
            position: 'right',
            formatter: '{c}%',
            color: '#07193F',
            fontWeight: 'bold',
            fontSize: 12,
          },
          data: _arr1
        }, ]
      };
      myOptions2 = option;
      myMap2.setOption(option);
      return myMap2
    });
  },
  // 年龄
  initAgeChart(F2, config, data) {
    let _dom = config;
    _dom.padding = [0, 10, 0, 50];
    const chart = new F2.Chart(_dom);
    const _data = data;
    _data.forEach(function (obj) {
      let textAlign;
      let offsetX;
      textAlign = 'start';
      offsetX = 5;
      chart.guide().text({
        position: [obj.name, obj.value],
        content: obj.value + '%',
        style: {
          textAlign,
          fill: '#07193F',
          fontWeight: 'bold',
          fontSize: 12
        },
        offsetX
      });
    });
    chart.source(_data.reverse(), {
      value: {
        min: 0,
        max: 100
      }
    });
    chart.coord({
      transposed: true
    });
    chart.axis('value', false);
    chart.axis('name', {
      grid: null,
      label: {
        fill: "#7789AF",
        fontSize: 12
      }
    });
    chart.interval().position('name*value').size(12);
    chart.render();
    return chart;
  },
  ageEcharts() {
    oneComponent3 = this.selectComponent('#ageCanvas');
    let that = this,
      _arr = [],
      _arr1 = [];
    for (let i = 0; i < this.data.ageList.length; i++) {
      _arr.unshift(this.data.ageList[i].name);
      _arr1.unshift(this.data.ageList[i].value);
    }
    oneComponent3.init((canvas, width, height, dpr) => {
      myMap3 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myMap3);
      const option = {
        grid: {
          show: false,
          left: 50,
          right: 5,
          bottom: 5,
          top: 0,
          containLabel: false
        },
        color: ["#1890FF"],
        xAxis: {
          show: false,
          type: 'value',
          max: 100,
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#7789AF',
              fontSize: 12
            }
          },
          data: _arr
        },
        series: [{
          type: 'bar',
          barWidth: 12,
          label: {
            show: true,
            position: 'right',
            formatter: '{c}%',
            color: '#07193F',
            fontWeight: 'bold',
            fontSize: 12,
          },
          data: _arr1
        }, ]
      };
      myOptions3 = option;
      myMap3.setOption(option);
      return myMap3
    });
  },
  // 消费
  initConsumeChart(F2, config, data) {
    let _dom = config;
    _dom.padding = [0, 10, 0, 55];
    const chart = new F2.Chart(_dom);
    const _data = data;
    _data.forEach(function (obj) {
      let textAlign;
      let offsetX;
      textAlign = 'start';
      offsetX = 5;
      chart.guide().text({
        position: [obj.name, obj.value],
        content: obj.value + '%',
        style: {
          textAlign,
          fill: '#07193F',
          fontWeight: 'bold',
          fontSize: 12
        },
        offsetX
      });
    });
    chart.source(_data.reverse(), {
      value: {
        min: 0,
        max: 100
      }
    });
    chart.coord({
      transposed: true
    });
    chart.axis('value', false);
    chart.axis('name', {
      grid: null,
      label: {
        fill: "#7789AF",
        fontSize: 12
      }
    });
    chart.interval().position('name*value').size(12);
    chart.render();
    return chart;
  },
  consumeEcharts() {
    oneComponent4 = this.selectComponent('#consumeCanvas');
    let that = this,
      _arr = [],
      _arr1 = [];
    for (let i = 0; i < this.data.consumeList.length; i++) {
      _arr.unshift(this.data.consumeList[i].name);
      _arr1.unshift(this.data.consumeList[i].value);
    }
    oneComponent4.init((canvas, width, height, dpr) => {
      myMap4 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myMap4);
      const option = {
        grid: {
          show: false,
          left: 55,
          right: 5,
          bottom: 5,
          top: 0,
          containLabel: false
        },
        color: ["#1890FF"],
        xAxis: {
          show: false,
          type: 'value',
          max: 100,
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#7789AF',
              fontSize: 12
            }
          },
          data: _arr
        },
        series: [{
          type: 'bar',
          barWidth: 12,
          label: {
            show: true,
            position: 'right',
            formatter: '{c}%',
            color: '#07193F',
            fontWeight: 'bold',
            fontSize: 12,
          },
          data: _arr1
        }, ]
      };
      myOptions4 = option;
      myMap4.setOption(option);
      return myMap4
    });
  },
  // 跳转商品详情
  onClick(e) {
    common.toDetail(e.currentTarget.dataset.id)
  },
  tabChange(event) {
    let _index = event.detail.index,
      that = this;
    // console.log(_index)
    this.setData({
      isHand: false,
    })
    if (_index == 0) {
      wx.pageScrollTo({
        selector: ".sale-trend",
        duration: 300
      })
    } else if (_index == 1) {
      wx.pageScrollTo({
        selector: ".life-cycle",
        duration: 300
      })
    } else if (_index == 2) {
      wx.pageScrollTo({
        selector: ".readers",
        duration: 300
      })
    } else if (_index == 3) {
      wx.pageScrollTo({
        selector: ".relation",
        duration: 300
      })
    }
    setTimeout(function () {
      that.setData({
        isHand: true,
      })
    }, 1000)
  },
  // 选择时间
  change(e) {
    this.setData({
      period: e.detail.period,
      date_type: e.detail.date_type,
      start_date: e.detail.start_date,
      time: e.detail.time,
    })
    wx.showLoading({
      mask: true
    })
    this.getKernelData();
  },
  changeChoose(e) {
    this.setData({
      choose: e.currentTarget.dataset.type,
      showKernel: false
    });
    let _arr = [];
    if (this.data.choose == 1) {
      _arr = this.data.saleTotalList;
    } else if (this.data.choose == 2) {
      _arr = this.data.saleRankList;
    } else if (this.data.choose == 3) {
      _arr = this.data.saleCateList;
    }
    this.setData({
      kernelChartList: _arr,
      onInitChart: (F2, config) => this.initKernelChart(F2, config, _arr),
      showKernel: true,
    })
    this.kernelEcharts();
  },
  mapChange(e) {
    // console.log(456, e)
    this.setData({
      visible: e.detail.visible
    })
    if (e.detail.visible) {
      // oneComponent = this.selectComponent('#chartmap');
      // // wx.nextTick(()=>{
      // this.initChartMap();
      // // })
    }
  },
  renderCanvas() {
    this.setData({
      shareShow: false,
    })
    // Toast('该页面暂未开放画报功能！')
    wx.showLoading({
      mask: false,
      title: "数据画报生成中"
    })
    let that = this;
    if (this.data.kernelChartList.length > 0) {
      this.canvasToUrl('#kernelCanvas', 0);
    } else if (this.data.leftChartList.length > 0) {
      this.canvasToUrl('#lifeCanvas', 1);
    } else if(this.data.basePower){
      this.canvasToUrl('#sexCanvas', 2);
    }else{
      this.canvasHtml(); 
    }
  },
  canvasToUrl(componentId, _index) {
    let width, height, destWidth, destHeight, _myMap, _myOptions, that = this,
      _arr = ['#kernelCanvas', '#lifeCanvas', '#sexCanvas', '#ageCanvas', '#consumeCanvas'];
    if (componentId == '#kernelCanvas') {
      _myMap = myMap;
      _myOptions = myOptions;
    } else if (componentId == '#lifeCanvas') {
      _myMap = myMap1;
      _myOptions = myOptions1;
    } else if (componentId == '#sexCanvas') {
      _myMap = myMap2;
      _myOptions = myOptions2;
    } else if (componentId == '#ageCanvas') {
      _myMap = myMap3;
      _myOptions = myOptions3;
    } else if (componentId == '#consumeCanvas') {
      _myMap = myMap4;
      _myOptions = myOptions4;
    }
    const query = wx.createSelectorQuery()
    query.select(componentId).boundingClientRect()
    query.exec(function (rects) {
      rects.forEach(function (rect, n) {
        width = rect.width;
        height = rect.height;
        destWidth = rect.width;
        destHeight = rect.height;
      })
      _myMap.on("finished", () => {
        console.log("开始转换")
        console.log(555, that.selectComponent(componentId).canvasToTempFilePath)

        that.selectComponent(componentId).canvasToTempFilePath({
          x: 0,
          y: 0,
          width,
          height,
          // 截取canvas的宽度
          destWidth,
          // 截取canvas的高度    
          destHeight,
          success: res => {
            console.log("转换图片成功", res.tempFilePath)
            if (componentId == '#kernelCanvas') {
              that.setData({
                kernelChartSrc: res.tempFilePath,
              })
            } else if (componentId == '#lifeCanvas') {
              that.setData({
                lifeChartSrc: res.tempFilePath,
              })
            } else if (componentId == '#sexCanvas') {
              that.setData({
                sexChartSrc: res.tempFilePath,
              })
            } else if (componentId == '#ageCanvas') {
              that.setData({
                ageChartSrc: res.tempFilePath,
              })
            } else if (componentId == '#consumeCanvas') {
              that.setData({
                consumeChartSrc: res.tempFilePath,
              })
            }
          },
          fail: res => {
            console.log("转换图片失败", res)
          },
          complete: res => {
            console.log("转换动作结束", res)
            // canvas 画图
            if (componentId == '#kernelCanvas') {
              if(that.data.leftChartList.length > 0){
                that.canvasToUrl(_arr[1], 1);
              }else{
                if(that.data.basePower){
                  that.canvasToUrl(_arr[2], 2);
                }else{
                  that.canvasHtml();
                }
              }
            } else if(componentId == '#lifeCanvas'){
              if (that.data.basePower) {
                that.canvasToUrl(_arr[2], 2);
              }else{
                that.canvasHtml();
              }
            }else if (componentId == '#sexCanvas') {
              that.canvasToUrl(_arr[3], 3);
            } else if (componentId == '#ageCanvas' ) {
              that.canvasToUrl(_arr[4], 4);
            } else if (componentId == '#consumeCanvas' ) {
              that.canvasHtml();
            } else {
              that.canvasHtml();
            }
          }
        });
      });
      _myMap.setOption(_myOptions);
    })
  },
  canvasHtml() {
    console.log('转换完成')
    this.widget = this.selectComponent('.widget');
    let wxml = '',
      that = this,
      _title = JSON.parse(wx.getStorageSync('currentOrganize')),
      _info = JSON.parse(wx.getStorageSync('initInfo'));
    wxml += `
      <view class="canvas-content">
        <view class="liubai"></view>`;
    wxml += `<view class="head">
              <text class="sjjb">品种详情</text>`
    if (_title.organization_name.length < 20) {
      wxml += `<text class="orgtitle">` + _title.organization_name + `</text>`;
    } else {
      wxml += `<text class="orgtitle">` + _title.organization_name.slice(0, 17) + '...' + `</text>`
    }
    wxml += `</view>`;
    if (this.data.infoPower) {
      let _src = this.data.baseInfo.cover_pic;
      if(_src.indexOf('https:') > -1){
        _src = this.data.baseInfo.cover_pic;
      }else{
        _src = this.data.baseInfo.cover_pic.replace(/http/,'https');
      }
      wxml += `<view class="goods-info">`;
            if(this.data.baseInfo.cover_pic){
              wxml += `<image class="image1" src="` + _src + `"></image>`
            }else{
              wxml += `<view class="no-image"></view>`
            }
            wxml += `<view class="goods-right">
                <view class="goods-titles"><text class="goods-title">` + this.data.baseInfo.title + `</text></view>`
      if (this.data.baseInfo.best_rank_info) {
        if (this.data.baseInfo.best_rank_info.length > 11) {
          wxml += `<view class="goods-tab1 width165"><text class="goods-best width165">` + this.data.baseInfo.best_rank_info + `</text></view>`;
        } else {
          wxml += `<view class="goods-tab1"><text class="goods-best">` + this.data.baseInfo.best_rank_info + `</text></view>`;
        }
      }
      let _sale;
      if (this.data.baseInfo.on_sale == 0) {
        _sale = '停售品种';
      } else if (this.data.baseInfo.sale_type == 1) {
        _sale = '新品品种';
      } else if (this.data.baseInfo.sale_type == 2) {
        _sale = '畅销品种';
      } else if (this.data.baseInfo.sale_type == 3) {
        _sale = '常销品种';
      } else if (this.data.baseInfo.sale_type == 4) {
        _sale = '一般品种';
      } else if (this.data.baseInfo.sale_type == 5) {
        _sale = '滞销品种';
      }
      wxml += `<view class="goods-tab2"><text class="goods-sale">` + _sale + `</text></view>`;
      wxml += `</view></view>`;
    } else {
      wxml += `<text class="nodata">暂无权限</text>`
    }
    wxml += `<view class="greyblock"></view>`;
    wxml += `<text class="zrxs">销售走势</text>`;
    wxml += `<view class="choosetime">
                <image class="image2" src="https://bodao.mhuoba.com/static/wximages/rili.png"></image>
                <text class="time">` + this.data.time + `</text>
              </view>`;
    if (this.data.chartPower) {
      wxml += `<view class="blocks">`;
      if (this.data.choose == 1) {
        wxml += `<view class="block active">`
      } else {
        wxml += `<view class="block">`
      }
      wxml += `<text class="block-num">` + this.data.kernelData.sale_total_info.now + `</text>
                <text class="block-text">销售指数</text>
              </view>`;
      if (this.data.choose == 2) {
        wxml += `<view class="block active">`
      } else {
        wxml += `<view class="block">`
      }
      wxml += `<text class="block-num">` + this.data.kernelData.sale_rank_info.now + `</text>
                <text class="block-text">行业排名</text>
              </view>`;
      if (this.data.choose == 3) {
        wxml += `<view class="block active">`
      } else {
        wxml += `<view class="block">`
      }
      wxml += `<text class="block-num">` + this.data.kernelData.sale_cate_rank_info.now + `</text>
                <text class="block-text">类目排名</text>
              </view>
            </view>`
      if (this.data.kernelChartList.length > 0) {
        wxml += `<image class="image3" src="` + this.data.kernelChartSrc + `"></image>`
      } else {
        wxml += `<text class="nodata">暂无图表数据</text>`
      }
    } else {
      wxml += `<text class="nodata two">暂无权限</text>`
    }
    wxml += `<view class="greyblock"></view>`;
    wxml += `<text class="zrxs">生命周期</text>`;
    if (this.data.historyChartPower) {
      let _duration;
      if (this.data.lifeInfo.publish_duration > 0) {
        _duration = this.data.lifeInfo.publish_duration + '个月';
      } else {
        _duration = '预售中';
      }
      wxml += `<view class="life-blocks">
              <view class="life-block">
                <text class="life-num">` + this.data.lifeInfo.sale_total + `</text>
                <text class="life-text">累计销售指数</text>
              </view>
              <view class="life-block">
                <text class="life-num">` + _duration + `</text>
                <text class="life-text">上市时长</text>
              </view>
            </view>`
      if (this.data.leftChartList.length > 0) {
        wxml += `<image class="image3" src="` + this.data.lifeChartSrc + `"></image>`
      } else {
        wxml += `<text class="nodata">暂无图表数据</text>`
      }
    } else {
      wxml += `<text class="nodata two">暂无权限</text>`
    }
    wxml += `<view class="greyblock"></view>`;
    wxml += `<text class="zrxs">读者画像</text>`;
    if (this.data.basePower) {
      wxml += `<text class="reader">性别</text>`;
      wxml += `<image class="image4" src="` + this.data.sexChartSrc + `"></image>`;
      wxml += `<text class="reader">年龄</text>`;
      wxml += `<image class="image5" src="` + this.data.ageChartSrc + `"></image>`;
      wxml += `<text class="reader">消费</text>`;
      wxml += `<image class="image6" src="` + this.data.consumeChartSrc + `"></image>`;
      wxml += `<text class="reader">地域</text>`;
      if (this.data.regionList1.length > 0) {
        wxml += `<view class="region">
              <view class="region-list">`;
        for (let i = 0; i < this.data.regionList1.length; i++) {
          wxml += `<view class="region-content">
                  <text class="region-rank">` + (i + 1) + '.' + this.data.regionList1[i].name + `</text>
                  <text class="region-ratio">` + this.data.regionList1[i].value + '%' + `</text>
                </view>`;
        }
        wxml += `</view>
              <view class="region-list">`;
        for (let i = 0; i < this.data.regionList2.length; i++) {
          wxml += `<view class="region-content">
                <text class="region-rank">` + (i + 6) + '.' + this.data.regionList2[i].name + `</text>
                <text class="region-ratio">` + this.data.regionList2[i].value + '%' + `</text>
              </view>`;
        }
        wxml += `</view>
            </view>`
      } else {
        wxml += `<text class="nodata one">暂无数据</text>`
      }
    }else{
      wxml += `<text class="nodata three">暂无权限</text>`
    }
    wxml += `<view class="zhichi">
              <image class="ercode" src="https://bodao.mhuoba.com/static/wximages/ercode.png"></image>
              <text class="jishu">博道出版数据实验室提供技术支持</text>
            </view>`;
    wxml += `</view>`;
    let style = {
      canvasContent: {
        backgroundColor: '#FFF',
        width: 375,
        height: 1290,
        padding: 10,
      },
      liubai: {
        width: 355,
        height: 20
      },
      head: {
        width: 355,
        height: 23,
        flexDirection: 'row',
        alignItems: 'center'
      },
      sjjb: {
        width: 68,
        height: 23,
        fontSize: 16,
        color: '#07193F',
      },
      orgtitle: {
        width: 280,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginLeft: 5
      },
      greyblock: {
        width: 375,
        height: 4,
        backgroundColor: '#F4F7FD',
        marginLeft: -10,
        marginTop: 15
      },
      goodsInfo: {
        width: 355,
        height: 100,
        flexDirection: 'row',
        marginTop: 5
      },
      image1: {
        width: 100,
        height: 100,
      },
      goodsRight: {
        width: 245,
        height: 100,
        marginLeft: 10,
      },
      goodsTitles: {
        width: 245,
        height: 40,
        marginBottom: 10
      },
      goodsTitle: {
        width: 245,
        height: 40,
        fontSize: 14,
        color: '#07193F'
      },
      goodsTab1: {
        width: 120,
        height: 21,
        backgroundColor: '#FFEBCC',
        borderRadius: 5,
      },
      goodsBest: {
        width: 120,
        height: 21,
        fontSize: 12,
        color: '#FF9900',
        textAlign: 'center',
        lineHeight: 21
      },
      goodsTab2: {
        width: 65,
        height: 21,
        backgroundColor: '#D1DDF6',
        borderRadius: 5,
        marginTop: 5,
      },
      goodsSale: {
        width: 65,
        height: 21,
        fontSize: 12,
        color: '#1754D2',
        textAlign: 'center',
        lineHeight: 21
      },
      zrxs: {
        width: 355,
        height: 20,
        fontSize: 14,
        color: '#07193F',
        marginTop: 10
      },
      choosetime: {
        width: 355,
        height: 18,
        marginTop: 5,
        flexDirection: 'row',
        alignItems: 'center',
      },
      image2: {
        width: 16,
        height: 16,
      },
      time: {
        width: 335,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginLeft: 5,
        marginTop: 2
      },
      blocks: {
        width: 355,
        height: 60,
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginTop: 10
      },
      block: {
        width: 110,
        height: 60,
        backgroundColor: '#F4F7FD',
        borderRadius: 4,
        flexDirection: 'column',
      },
      active: {
        borderWidth: 2,
        borderColor: '#7498E4',
      },
      blockNum: {
        width: 110,
        height: 24,
        fontSize: 16,
        color: '#07193F',
        textAlign: 'center',
        marginTop: 10
      },
      blockText: {
        width: 110,
        height: 20,
        fontSize: 12,
        color: '#7789AF',
        textAlign: 'center',
      },
      image3: {
        width: 355,
        height: 100,
        marginTop: 5,
      },
      lifeBlocks: {
        width: 355,
        height: 60,
        flexDirection: 'row',
        marginTop: 10
      },
      lifeBlock: {
        width: 120,
        height: 45,
        flexDirection: 'column',
      },
      lifeNum: {
        width: 120,
        height: 24,
        fontSize: 16,
        color: '#07193F',
      },
      lifeText: {
        width: 120,
        height: 20,
        fontSize: 12,
        color: '#7789AF',
      },
      reader: {
        width: 355,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginTop: 10
      },
      image4: {
        width: 355,
        height: 70,
        marginBottom: 5
      },
      image5: {
        width: 355,
        height: 138,
        marginBottom: 5
      },
      image6: {
        width: 355,
        height: 90,
        marginBottom: 5
      },
      region: {
        width: 355,
        height: 115,
        flexDirection: 'row',
      },
      regionList: {
        width: 175,
        height: 115,
        flexDirection: 'column',
      },
      regionContent: {
        width: 175,
        height: 23,
        flexDirection: 'row',
        justifyContent: 'space-between'
      },
      regionRank: {
        width: 85,
        height: 23,
        fontSize: 12,
        color: '#7789AF'
      },
      regionRatio: {
        width: 85,
        height: 23,
        fontSize: 12,
        color: '#07193F',
      },
      zhichi: {
        width: 355,
        height: 78,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: "center",
      },
      ercode: {
        width: 48,
        height: 48,
      },
      jishu: {
        width: 180,
        height: 18,
        color: '#07193F',
        fontSize: 12,
        marginLeft: 15
      },
      noImage:{
        width: 100,
        height: 100,
        backgroundColor:'#D1DDF6'
      },
      nodata: {
        width: 355,
        height: 100,
        lineHeight: 100,
        color: '#7789AF',
        fontSize: 12,
        textAlign: 'center',
      },
      one: {
        height: 115,
        lineHeight: 115,
      },
      two: {
        height: 160,
        lineHeight: 160,
      },
      three:{
        height: 520,
        lineHeight: 520,
      },
      width165: {
        width: 165
      }
    }
    console.log(22, {
      wxml,
      style
    });
    const p1 = this.widget.renderToCanvas({
      wxml,
      style
    })
    p1.then((res) => {
      // console.log('canvasContent', res)
      this.canvasContent = res
      wx.hideLoading();
      Dialog.confirm({
          title: '',
          message: '画报生成成功，是否保存至手机相册',
        })
        .then(() => {
          // on confirm
          that.extraImage();
        })
        .catch(() => {
          // on cancel
        });
    })
  },
  extraImage() {
    let that = this;
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      console.log('最后1', res.tempFilePath)
      that.setData({
        src: res.tempFilePath,
        width: this.canvasContent.layoutBox.width,
        height: this.canvasContent.layoutBox.height
      })
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          console.log('保存图片成功', res)
          Toast('成功保存至手机相册！')
        },
        fail(res) {
          console.log('保存图片失败', res)
          Toast('保存至手机相册失败！')
        },
        complete(res) {
          console.log('保存图片动作结束', res)
          wx.hideLoading();
        }
      })
    })
  },
  touchMove() {
    // console.log(1);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchCancel() {
    // console.log(2);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchEnd() {
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  onPageScroll: function (e) {
    // console.log(e)
    let that = this;
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
    if (this.data.isHand) {
      let topHeight = this.data.topHeight,
          trendHeight = this.data.trendHeight,
          lifeHeight = this.data.lifeHeight,
          readerHeight = this.data.readerHeight;
      if (e.scrollTop < (topHeight + trendHeight)) {
        this.setData({
          active: 0
        })
      } else if (e.scrollTop < (topHeight + trendHeight + lifeHeight + 20) && e.scrollTop > (topHeight + trendHeight)) {
        this.setData({
          active: 1
        })
      } else if (e.scrollTop < (topHeight + trendHeight + lifeHeight + readerHeight +20) && e.scrollTop > (topHeight + trendHeight + lifeHeight + 20)) {
        this.setData({
          active: 2
        })
      } else if ((topHeight + trendHeight + lifeHeight + readerHeight + 40) < e.scrollTop) {
        this.setData({
          active: 3
        })
      }
      setTimeout(() => {
        var animation = wx.createAnimation({
          duration: 500
        })
        animation.translateX('0').step();
        this.setData({
          animationData: animation.export()
        });
      }, 2000)
      // console.log(this.data.active)
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goodsId: options.id
      // goodsId: 3343722
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // console.log(111)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync("token")) {
      let _title = JSON.parse(wx.getStorageSync('currentOrganize')),
        that = this;
      wx.setNavigationBarTitle({
        title: _title.organization_name,
      })
      this.setData({
        active: 0,
        isHand: false,
      })
      wx.showLoading({
        mask: true
      })
      this.getBaseInfo();
      this.getKernelData();
      this.getLifeInfo();
      this.getLifeChartData();
      this.getReaderData();
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      setTimeout(function () {
        that.setData({
          isHand: true,
        })
      }, 1000)
    } else {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.hideLoading();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "博道出版数据实验室"
    }
  }
})